import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:get/get.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:jinke/utils/colors_util.dart';
import 'package:dio/dio.dart' as dio;
import 'package:jinke/utils/httputils/api.dart';
import '../../../global/FilePathEntity.dart';
import '../../../utils/httputils/resultdata.dart';
import 'state.dart';

class EditAttractLogic extends GetxController {
  final EditAttractState state = EditAttractState();




  //文件选择
  void pickFiles() async{
    // FilePickerResult? result = await FilePicker.platform.pickFiles(
    //   type: FileType.custom,
    //   allowedExtensions: ['jpg', 'pdf', 'doc'],
    // );

    FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);

    if (result != null) {
      List<File> files = result.paths.map((path) => File(path!)).toList();
    } else {
      // User canceled the picker
    }
  }

  ///选择多张图片 Select multiple images
  Future<void> selectImages() async {

    state.listImagePaths = await ImagePickers.pickerPaths(
        galleryMode: GalleryMode.image,
        selectCount: 9,
        showGif: true,
        showCamera: true,
        compressSize: 500,
        uiConfig: UIConfig(uiThemeColor: ColorsUtil.blue),
        cropConfig: CropConfig(enableCrop: false, width: 2, height: 1));



        state.multipartFiles.clear();
      for(int i=0;i<state.listImagePaths.length;i++){
        state.multipartFiles.add(dio.MultipartFile.fromFileSync(state.listImagePaths[i].path!));
      }

    update();

  }



  commit() async{

    if(state.multipartFiles.isNotEmpty){
      await postUploadFiles();
    }

    var params = [{'content': state.content, 'submitStatus': 1, 'startTime': "",'files':state.filePathEntity??[]}];

    ResultData response = await Api.saveWorks(params);

    if (response.isSuccess) {
      Get.back(result: true);
    }
  }


  /// 多文件上传接口
  Future<List<FilePathEntity>?> postUploadFiles() async {

    ResultData resultData =
    await Api.postUploadFiles(state.multipartFiles);
    List<dynamic> list = resultData.data;
    state.filePathEntity = list.map((e) => FilePathEntity.fromJson(e)).toList();
    return state.filePathEntity;
  }

}
